﻿using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using YGBookmark.Models;
using YGBookmark.DAL;
using System.ComponentModel.DataAnnotations;
using System.Data.SQLite;
using YGBookmark.Utils;

namespace YGBookmark.UI
{
    /// <summary>
    /// 标签管理窗体（包含完整CRUD操作和实时搜索）
    /// </summary>
    public partial class TagManagerForm : Form
    {
        #region 控件声明
        private DataGridView dgvTags;
        private TextBox txtSearch;
        private Button btnAdd;
        private Button btnEdit;
        private Button btnDelete;
        private Button btnRefresh;
        #endregion

        public TagManagerForm()
        {
            InitializeComponent();
            InitializeUI();
            LoadTags();
        }

        private void InitializeComponent()
        {
            // 此方法由Windows Forms设计器生成
            // 实际项目中应通过设计器自动生成
            // 此处为兼容手写代码的简化实现
            this.SuspendLayout();

            // 窗体属性设置
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(784, 561);
            this.Name = "TagManagerForm";

            this.ResumeLayout(false);
        }

        #region UI初始化
        private void InitializeUI()
        {
            // 窗体设置
            this.Text = "标签管理";
            this.Size = new Size(800, 600);
            this.StartPosition = FormStartPosition.CenterParent;

            // 主布局容器
            var mainTable = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 1,
                RowCount = 2
            };

            // 顶部工具栏
            var toolPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Top,
                FlowDirection = FlowDirection.LeftToRight,
                Height = 40
            };

            // 搜索框
            txtSearch = new TextBox
            {
                Width = 200,
                PlaceholderText = "输入标签名称过滤...",
                Margin = new Padding(5)
            };
            txtSearch.TextChanged += (s, e) => FilterTags();

            // 按钮初始化
            btnAdd = CreateToolButton("➕ 添加", AddTag);
            btnEdit = CreateToolButton("✏️ 编辑", EditTag);
            btnDelete = CreateToolButton("❌ 删除", DeleteTag);
            btnRefresh = CreateToolButton("🔄 刷新", () => LoadTags());

            // 数据表格
            dgvTags = new DataGridView
            {
                Dock = DockStyle.Fill,
                ReadOnly = true,
                AllowUserToAddRows = false,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect
            };
            ConfigureColumns();

            // 组合控件
            toolPanel.Controls.AddRange(new Control[]
            {
                btnAdd, btnEdit, btnDelete, btnRefresh, txtSearch
            });

            mainTable.Controls.Add(toolPanel, 0, 0);
            mainTable.Controls.Add(dgvTags, 0, 1);

            this.Controls.Add(mainTable);
        }

        private Button CreateToolButton(string text, Action action)
        {
            return new Button
            {
                Text = text,
                AutoSize = true,
                Margin = new Padding(5),
                FlatStyle = FlatStyle.Flat,
                BackColor = Color.WhiteSmoke,
                Cursor = Cursors.Hand
            }.WithClick(action);
        }

        private void ConfigureColumns()
        {
            dgvTags.Columns.AddRange(
                new DataGridViewTextBoxColumn
                {
                    HeaderText = "ID",
                    DataPropertyName = "Id",
                    Width = 50
                },
                new DataGridViewTextBoxColumn
                {
                    HeaderText = "标签名称",
                    DataPropertyName = "Name"
                },
                new DataGridViewTextBoxColumn
                {
                    HeaderText = "创建时间",
                    DataPropertyName = "CreateTime",
                    DefaultCellStyle = new DataGridViewCellStyle
                    {
                        Format = "yyyy-MM-dd HH:mm"
                    }
                },
                new DataGridViewTextBoxColumn
                {
                    HeaderText = "使用次数",
                    DataPropertyName = "UsageCount"
                }
            );
        }
        #endregion

        #region 数据操作
        private async void LoadTags()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                var tags = await DatabaseHelper.Instance.ExecuteQueryAsync<Tag>(
                    "SELECT * FROM Tags ORDER BY CreateTime DESC");

                dgvTags.DataSource = tags;
                UpdateUIState();
            }
            catch (Exception ex)
            {
                ShowError("加载标签失败: " + ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void FilterTags()
        {
            if (dgvTags.DataSource is not BindingSource source) return;

            var filter = string.IsNullOrEmpty(txtSearch.Text)
                ? ""
                : $"Name LIKE '%{txtSearch.Text.Replace("'", "''")}%'";

            source.Filter = filter;
            UpdateUIState();
        }
        #endregion

        #region 业务逻辑
        private void AddTag()
        {
            using var inputForm = new InputDialog("新建标签", "请输入标签名称:");
            if (inputForm.ShowDialog() == DialogResult.OK)
            {
                var newTag = new Tag(inputForm.InputText);
                if (ValidateTag(newTag))
                {
                    //newTag.CreateTime = DateTime.Now;
                    DatabaseHelper.Instance.ExecuteNonQuery(
                        "INSERT INTO Tags (Name,CreateTime) VALUES (@name,@createTime)",
                        new SQLiteParameter("@name", newTag.Name),
                        new SQLiteParameter("@createTime", newTag.CreateTime.GetDtStr())
                        );

                    LoadTags();
                }
            }
        }

        private void EditTag()
        {
            if (dgvTags.SelectedRows.Count == 0) return;

            var selectedTag = dgvTags.SelectedRows[0].DataBoundItem as Tag;
            using var inputForm = new InputDialog("编辑标签", "修改标签名称:", selectedTag.Name);

            if (inputForm.ShowDialog() == DialogResult.OK)
            {
                selectedTag.Name = inputForm.InputText.Trim();
                if (ValidateTag(selectedTag))
                {
                    DatabaseHelper.Instance.ExecuteNonQuery(
                        "UPDATE Tags SET Name = @name WHERE Id = @id",
                        new SQLiteParameter("@name", selectedTag.Name),
                        new SQLiteParameter("@id", selectedTag.Id));

                    LoadTags();
                }
            }
        }

        private void DeleteTag()
        {
            if (dgvTags.SelectedRows.Count == 0) return;

            var selectedTag = dgvTags.SelectedRows[0].DataBoundItem as Tag;
            if (MessageBox.Show($"确定要删除标签 '{selectedTag.Name}' 吗？",
                "确认删除", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    DatabaseHelper.Instance.ExecuteNonQuery(
                        "DELETE FROM Tags WHERE Id = @id",
                        new SQLiteParameter("@id", selectedTag.Id));

                    LoadTags();
                }
                catch (SQLiteException ex) when (ex.ResultCode == SQLiteErrorCode.Constraint)
                {
                    ShowError("该标签正在被使用，无法删除！");
                }
            }
        }

        private bool ValidateTag(Tag tag)
        {
            var context = new ValidationContext(tag);
            var results = new List<ValidationResult>();

            if (!Validator.TryValidateObject(tag, context, results, true))
            {
                ShowError(string.Join("\n", results.Select(r => r.ErrorMessage)));
                return false;
            }

            // 检查名称唯一性
            var existing = DatabaseHelper.Instance.ExecuteScalar(
                "SELECT COUNT(*) FROM Tags WHERE Name = @name AND Id != @id",
                new SQLiteParameter("@name", tag.Name),
                new SQLiteParameter("@id", tag.Id));

            if (Convert.ToInt32(existing) > 0)
            {
                ShowError("标签名称已存在！");
                return false;
            }

            return true;
        }
        #endregion

        #region 辅助方法
        private void UpdateUIState()
        {
            bool hasSelection = dgvTags.SelectedRows.Count > 0;
            btnEdit.Enabled = hasSelection;
            btnDelete.Enabled = hasSelection;
        }

        private void ShowError(string message)
        {
            MessageBox.Show(message, "操作失败",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        // 输入对话框类
        private class InputDialog : Form
        {
            public string InputText => txtInput.Text.Trim();
            private readonly TextBox txtInput;

            public InputDialog(string title, string prompt, string defaultValue = "")
            {
                this.Text = title;
                this.Size = new Size(300, 150);
                this.FormBorderStyle = FormBorderStyle.FixedDialog;
                this.StartPosition = FormStartPosition.CenterParent;

                var layout = new TableLayoutPanel
                {
                    Dock = DockStyle.Fill,
                    RowCount = 3,
                    ColumnCount = 1
                };

                var lblPrompt = new Label { Text = prompt, Dock = DockStyle.Fill };
                txtInput = new TextBox { Text = defaultValue, Dock = DockStyle.Fill };
                var btnPanel = new FlowLayoutPanel
                {
                    Dock = DockStyle.Fill,
                    FlowDirection = FlowDirection.RightToLeft
                };

                btnPanel.Controls.AddRange(new Control[]
                {
                    new Button { Text = "确定", DialogResult = DialogResult.OK },
                    new Button { Text = "取消", DialogResult = DialogResult.Cancel }
                });

                layout.Controls.Add(lblPrompt, 0, 0);
                layout.Controls.Add(txtInput, 0, 1);
                layout.Controls.Add(btnPanel, 0, 2);

                this.Controls.Add(layout);
                this.AcceptButton = btnPanel.Controls[0] as Button;
                this.CancelButton = btnPanel.Controls[1] as Button;
            }
        }
        #endregion
    }

    #region 扩展方法
    public static partial class ControlExtensions
    {
        public static Button WithClick(this Button button, Action action)
        {
            button.Click += (s, e) => action();
            return button;
        }
    }
    #endregion
}